//
//  MAOrganizationViewController.m
//  meiang_edu
//
//  Created by 贾倍 on 2019/1/3.
//  Copyright © 2019 com.meiang.meiang_edu. All rights reserved.
//

#import "MAOrganizationViewController.h"
#import "MAJiGouModel.h"
#import "OssService.h"
#import "NSString+Js.h"

@interface MAOrganizationViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *bgIcon;
@property (weak, nonatomic) IBOutlet UIImageView *faceIcon;
@property (weak, nonatomic) IBOutlet UITextField *jigouMCTF;
@property (weak, nonatomic) IBOutlet UITextField *jigouFLTF;

@property (strong, nonatomic) UIActionSheet *actionSheet;
/** bgImgUrl */
@property(nonatomic,copy) NSString *bgImgUrl;
/** faceImgUrl */
@property(nonatomic,copy) NSString *faceImgUrl;

@end

@implementation MAOrganizationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupBasic];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)setupBasic {
    self.title = @"编辑详情";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(saveDidClick) image:@"savebutton_logo" highImage:@"savebutton_logo"];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 4)];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.backgroundColor = PROJECT_LIGHT_GRAY_COLOR;
    
    
    [self.bgIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,self.jigouModel.cbackground]] placeholderImage:[UIImage imageNamed:@""]];
    
    [self.faceIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,self.jigouModel.ps_id]] placeholderImage:[UIImage imageNamed:@"homepage_navigationbar_picture"]];
    self.jigouMCTF.text = self.jigouModel.ccaption;
    self.jigouFLTF.text = self.jigouModel.ortype;
//    self.jigouFLTF
}

- (void)saveDidClick {
    DLog(@"");
    NSString *input = self.jigouMCTF.text;
    NSString *ortype = self.jigouFLTF.text;
    NSLog(@"%@",ortype);
    if (!input.length) {
        [MBManager showBriefAlert:@"名称不能为空"];
        return;
    }
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    //    "id": "F1CA5DB2-083A-47AD-82A3-B35757B899FB",//组织ID
    //    "ccode": "JG0001", //组织编号
    //    "ccaption": "祥瑞园小学", //组织蒙城
    //    "ortype": "1",组织类型
    //    "ps_id": "ACC25294-0502-4957-9CF3-3BE6A5F4DB99",//头像ID
    //    "cnotes": "体魄7名明灭很感兴趣",
    //    "cbackground": "a7c69f92-f94f-466c-ac99-63ebf1295c73", //背景ID
    
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    
    body[@"id"] = self.jigouModel.ID;
    body[@"ccode"] = self.jigouModel.ccode;
    body[@"ccaption"] = input;
    body[@"ortype"] = ortype;
    body[@"ortype"] = self.jigouModel.ortype;
    body[@"cnotes"] = self.jigouModel.cnotes;
    body[@"ps_id"] = self.faceImgUrl.length ? self.faceImgUrl : self.jigouModel.ps_id;
    body[@"cbackground"] = self.bgImgUrl.length ? self.bgImgUrl : self.jigouModel.cbackground;
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:ORGANIZATION_UPDATE parameters:nil error:nil];
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setValue:@"token" forHTTPHeaderField:userinfo.token];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
                self.jigouModel.ccaption = self.jigouMCTF.text;
                self.jigouModel.ortype = self.jigouFLTF.text;
                if (self.faceImgUrl.length) {
                    self.jigouModel.ps_id = self.faceImgUrl;
                }
                if (self.bgImgUrl.length) {
                    self.jigouModel.cbackground = self.bgImgUrl;
                }
                self.navigationItem.rightBarButtonItem = nil;
            } else {
                [MBManager showBriefAlert:message];
            }
            DLog(@"Reply JSON: %@", responseObject);
            
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}

#pragma mark - Table view data source
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    if (row == 0) { // 更换背景
        [self chooseIcon];
        DLog(@"");
    } else if (row == 1) { // 更换logo
        DLog(@"");
        [self chooseIcon];
    } else {
        DLog(@"机构分类");
    }
}

/**
 * 选择图片
 */
- (void)chooseIcon
{
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择",nil];
    }else{
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消"destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",nil];
    }
    
    self.actionSheet.tag = 1000;
    [self.actionSheet showInView:self.view];
}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 1000) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 0:
                    //来源:相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //来源:相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    return;
            }
        }
        else {
            if (buttonIndex == 1) {
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    DLog(@"===========%ld",indexPath.row);
    
    // 上传头像
    OssService *ossService = [[OssService alloc] initWithEndPoint:OSS_ENDPOINT];
    NSString *category = OSS_CATEGORY;
    NSString *type = @"jpg";
    long long int timevalue = (long long int)([NSDate date].timeIntervalSince1970 * 1000);
    // 自己拼接key，用于标识对象。
    
    NSString *objectKey = [NSString uuidString];
    [ossService asyncPutImage:objectKey data:UIImageJPEGRepresentation(img, 0.5) success:^(NSString *imgUrl){
        DLog(@"%@",imgUrl);
        if (indexPath.row == 0) { // 背景
            self.bgImgUrl = [[imgUrl componentsSeparatedByString:IMG_OSS] lastObject];
            [self.bgIcon sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
        } else { // 头像
            self.faceImgUrl = [[imgUrl componentsSeparatedByString:IMG_OSS] lastObject];
            [self.faceIcon sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
        }
    } failure:^(NSString *errmsg, NSString *objectKey, NSData *uploadData) {
        DLog(@"%@",errmsg);
    }];
}

#pragma mark - getter & setter
- (void)setJigouModel:(MAJiGouModel *)jigouModel {
    _jigouModel = jigouModel;
}


@end
